var mongoose = require('mongoose');
var User = require('../models/user.model');
var Upload = require('../models/upload.model');
var path=require('path');
var multer=require('multer');

var storage=multer.diskStorage({
    destination:function(req,file,cb){
        cb(null,'./uploads');
    },
    filename:function(req,file,cb){
        cb(null,file.fieldname+'-'+Date.now()+path.extname(file.originalname))
    }
})

var upload=multer({storage:storage})

exports.upload=function(req,res,next){
    var upload=multer({
        storage:storage,
        fileFilter:function(req,file,callback){
            var ext=path.extname(file.originalname);
            if(ext !=='.png' && ext !=='.jpg' && ext !=='.gif' ){
                return callback(res.end('文件类型不符'));
            }

            callback(null,true);
        }
    }).single('avatar')
    upload(req,res,function(err){

        var upload=new Upload(req.file);
        
        upload.save()
        .then(data=>{
            res.json(data);
        });
        res.end('file uploaded');
    });
}

exports.login = function(req,res,next){
   var name=req.body.name;
   var password=req.body.password;
   var data={name:name,password:password};

   User.findOne(data,function(err,result){
        res.json(result);
   })


    
}


// 新增
exports.create = function(req,res,next){
    var user = new User(req.body);

    user.save()
    .then(data=>{
        res.json(data)
    })
    
}

//修改
exports.update = function(req,res,next){
  
    var id = req.params.id; // 取Id
    User.findByIdAndUpdate(id,{$set: req.body}, {new:false} )
    .then(data=>{
        res.json(data); // data返回的是你之前修改的那个数据内容
    })
}

//删除
exports.remove = function(req,res,next){
    var id = req.params.id;
    User.findByIdAndRemove(id,function(err,doc){
        res.json({msg:'数据删除成功',status:200})
    })
} 


exports.list = function(req,res,next){
    var page = (req.body.page) ? parseInt(req.body.page) : 1;
    var limit = (req.body.limit) ? parseInt(req.body.limit) : 2;
    var queryCondition = {};
    var name;
    if( req.body.name && req.body.name.trim().length>0 ){
        name = req.body.name;
        queryCondition = {"name":new RegExp(name,'i')}
    }

    User.paginate(queryCondition, { page: parseInt(page), limit: parseInt(limit) }, function(err, result) {
        result.limit = result.docs;
        delete result.docs;

       res.json(result)
    });
}